/**
 * 1.公私钥对
 * 2.公钥直接当成地址用（或者截取公钥前20位）
 * 3.公钥通过私钥计算出来
 * */
const fs = require('fs')
const EC = require('elliptic').ec;

const ec = new EC('secp256k1');

let keypair = ec.genKeyPair();


function getPub(prv) {
  // 根据私钥算出公钥
  return ec.keyFromPrivate(prv).getPublic('hex').toString()
}

const keys = generateKeys()
console.log(keys)
// 1.获取公私钥对（持久化）
function generateKeys() {
  const fileName = './wallet.json'
  try {
    let keys = JSON.parse(fs.readFileSync(fileName))
    if (keys.prv && keys.pub && getPub(keys.prv) == keys.pub) {
      keypair = ec.keyFromPrivate(keys.prv)
      return keys
    } else {
      //  验证失败 重新生成
      throw 'no valid wallet.json'
    }
  } catch (error) {
    console.log(error)
    // 文件不存在或者文件内容不合法 重新生成
    const keys = {
      prv: keypair.getPrivate('hex').toString(), // 私钥
      pub: keypair.getPublic('hex').toString(), // 公钥
    }
    fs.writeFileSync(fileName, JSON.stringify(keys))
    return keys
  }
}

// 2.签名
function sign({from, to, amount, timestamp}) {
  const bufferMsg = Buffer.from(`${timestamp}-${amount}-${from}-${to}`)
  let signature = Buffer.from(keypair.sign(bufferMsg).toDER()).toString('hex')
  return signature
}

// 3.校验签名
function verify({
  from,
  to,
  amount,
  timestamp,
  signature
}, pub) {
  // 校验是没有私钥的
  const keypairTemp = ec.keyFromPublic(pub, 'hex')
  const bufferMsg = Buffer.from(`${timestamp}-${amount}${from}-${to}`)
  console.log(bufferMsg)
  console.log(signature)
  return keypairTemp.verify(bufferMsg, signature)
}

module.exports = { sign, verify, keys }

// const trans = {
//   from: 'heshuai',
//   to: 'heshuai1',
//   amount: 10
// }
// // const trans1 = {from: 'heshuai', to: 'heshuai1', 10}
// const signature = sign(trans)

// trans.signature = signature
// const isVerify = verify(trans, keys.pub)
// console.log(isVerify)